﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using SimpleTiles.Classes;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Scheduler;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.IO;

namespace SimpleTiles
{
    public partial class NotePage : PhoneApplicationPage
    {
        
        private bool addSveglia;
        private Note toModify {get;set;}
        private Boolean Caricato = false;
        private string titolo = null;

        public NotePage()
        {
            InitializeComponent();
        }
        

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!Caricato)
            {
                Caricato = true;

                addSveglia = false;

                datePicker.Value = DateTime.Now;
                timePicker.Value = DateTime.Now;

                //this.datePicker.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(datePicker_ValueChanged);
                //this.timePicker.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(timePicker_ValueChanged);

                DataContext = ColorExtensions.AccentColors();

                if(NavigationContext.QueryString.ContainsKey("titolo"))
                    titolo = NavigationContext.QueryString["titolo"]; 

                if (titolo == null)
                {
                    this.addNoteButton.Content = "addNote";
                }
                else
                {
                    toModify = App.nm.getByTitolo(titolo);

                    IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                    String imgPath = "/Shared/ShellContent/" + this.toModify.Titolo + ".jpg";
                    if (storage.FileExists(imgPath))
                    {
                        //Uri uri = new Uri("/Shared/ShellContent/" + this.toModify.Titolo + ".jpg", UriKind.Absolute);
                        BitmapImage bitmapImage = new BitmapImage();

                        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(imgPath, FileMode.Open, FileAccess.Read))
                            {
                                bitmapImage.SetSource(fileStream);
                            }
                        }

                        WriteableBitmap img = new WriteableBitmap(bitmapImage);
                        App.CroppedImage = img;
                    }
                    this.addNoteButton.Content = "saveNote";

                    this.nameNote.Text = this.toModify.Titolo;
                    this.nameNote.IsReadOnly = true;

                    this.checkBox1.IsChecked = this.toModify.FontPostIt;

                    this.textNoteBox.Text = this.toModify.Testo;
                    slider1.Value = this.toModify.slideFontSize;
                    //QUI
                    //this.ListColor.SelectedItem = toModify.theme;
                    DataContext = ColorExtensions.AccentColors(toModify.theme);

                    // se esiste una sveglia setta tutta la merda come ha fatto dokkis XD scherzo
                    if (toModify.Reminder)
                    {
                        datePicker.Value = toModify.Data;
                        timePicker.Value = toModify.Ora;
                        DateTime tp = (DateTime)this.timePicker.Value;
                        DateTime d = new DateTime(((DateTime)datePicker.Value).Year, ((DateTime)datePicker.Value).Month, ((DateTime)datePicker.Value).Day, tp.Hour, tp.Minute, tp.Second);
                        svegliaButton.Content = "disattiva sveglia";
                        addSveglia = true;
                    }
                }
            }

            if (App.CroppedImage != null)
            {
                imagePhoto.Source = App.CroppedImage;
            }
            base.OnNavigatedTo(e);
        }

        private void addNoteButton_Click(object sender, RoutedEventArgs e)
        {
            bool inModify = titolo!=null;

            //PhoneApplicationService.Current.State.Remove("noteNameID");
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
            var filename = "/Shared/ShellContent/note" + this.nameNote.Text + ".jpg";
            if (inModify)
                storage.DeleteFile(filename);
            var tileimg = "/Shared/ShellContent/" + this.nameNote.Text + ".jpg";
            if (inModify)
                storage.DeleteFile(tileimg);
            if (!storage.FileExists(filename) && !this.nameNote.Text.Equals(""))
            {
                if (addSveglia)
                {

                    if (ScheduledActionService.Find(this.nameNote.Text) != null)
                        ScheduledActionService.Remove(this.nameNote.Text);

                    DateTime data = (DateTime)this.datePicker.Value;
                    DateTime tp = (DateTime)this.timePicker.Value;
                    DateTime d = new DateTime(data.Year, data.Month, data.Day, tp.Hour, tp.Minute, tp.Second);

                    Reminder r = new Reminder(this.nameNote.Text)
                    {
                        Content = "Remind Me",
                        BeginTime = d,
                        Title = this.nameNote.Text
                    };
                    ScheduledActionService.Add(r);
                }
                else
                {

                    if (ScheduledActionService.Find(this.nameNote.Text) != null)
                        ScheduledActionService.Remove(this.nameNote.Text);
                }


                // Aggiungo le note
                if (App.CroppedImage != null)
                {
                    TileManager.WriteBitmap(App.CroppedImage, this.nameNote.Text);
                }

                WriteableBitmap bmp = new WriteableBitmap(173, 173);
                bmp.Render(gridTile, null);
                bmp.Invalidate();


                TileManager.WriteBitmap(bmp, "note" + this.nameNote.Text);
                if (!inModify)
                {
                    Note note = new Note(this.nameNote.Text, this.textNoteBox.Text, (DateTime)this.datePicker.Value, (DateTime)this.timePicker.Value, "/Shared/ShellContent/" + this.nameNote.Text + ".jpg", (Boolean)this.checkBox1.IsChecked, this.slider1.Value, this.ListColor.SelectedItem as String);
                    App.nm.addNote(note);
                    note.Update();
                }
                else
                {
                    toModify.Titolo = this.nameNote.Text;
                    toModify.Testo = this.textNoteBox.Text;
                    toModify.Data = (DateTime)this.datePicker.Value;
                    toModify.Ora = (DateTime)this.timePicker.Value;
                    toModify.FotoURL = "/Shared/ShellContent/" + this.nameNote.Text + ".jpg";
                    toModify.FontPostIt = (Boolean)this.checkBox1.IsChecked;
                    toModify.slideFontSize = this.slider1.Value;
                    toModify.theme = this.ListColor.SelectedItem as String;

                    toModify.Update();
                    TileManager.updateTile(toModify);
                }
                App.nm.saveNotes();
                App.CroppedImage = null;
                NavigationService.GoBack();
            }
            else
            {
                MessageBox.Show("Nome della nota non valido poichè vuoto o già esistente", "Info", MessageBoxButton.OK);
            }
        }
          
    

        private void addPhotoButton_Click(object sender, RoutedEventArgs e)
        {
           
            Microsoft.Phone.Tasks.
                CameraCaptureTask task = new CameraCaptureTask();
                task.Show();
                task.Completed += new EventHandler<PhotoResult>(task_Completed);

            //NavigationService.Navigate(new Uri("/CropImage.xaml", UriKind.Relative));
        }
        private void addImageButton_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask task = new PhotoChooserTask();
            task.Show();
            task.Completed += new EventHandler<PhotoResult>(task_Completed);
        }

        void task_Completed(object sender, PhotoResult e)
        {
            try
            {
                if (e != null)
                {
                    if (e.TaskResult == TaskResult.OK)
                    {
                        BitmapImage image = new BitmapImage();
                        image.SetSource(e.ChosenPhoto);

                        App.ChosenPhoto = new WriteableBitmap(image);

                        //PhoneApplicationService.Current.State["photo"] = image;

                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                             NavigationService.Navigate(new Uri("/CropImage.xaml", UriKind.Relative));
                        }); 
                    }
                    else if (e.Error is InvalidOperationException)
                    {
                        throw e.Error;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show("The Zune software is running. Please close Zune or disconnect the phone.", "Error", MessageBoxButton.OK);
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //setReminder((DateTime)this.datePicker.Value);
            if (!addSveglia)
            {
                DateTime data = (DateTime)this.datePicker.Value;
                DateTime tp = (DateTime)this.timePicker.Value;
                DateTime d = new DateTime(data.Year, data.Month, data.Day, tp.Hour, tp.Minute, tp.Second);

                if (d.CompareTo(DateTime.Now) > 0)
                {
                    addSveglia = true;
                    svegliaButton.Content = "disattiva sveglia";
                }
                else
                {
                    MessageBox.Show("Data della sveglia passata!", "Error", MessageBoxButton.OK);
                }
                
            }
            else 
            {
                addSveglia = false;
                svegliaButton.Content = "attiva sveglia";
               
            }

        }

       /* public void setReminder(DateTime data)
        {
            if (addSveglia)
            {
                DateTime tp = (DateTime)this.timePicker.Value;
                DateTime d = new DateTime(data.Year, data.Month, data.Day, tp.Hour, tp.Minute, tp.Second);

                if (d.CompareTo(DateTime.Now) > 0)
                {
                    addSveglia = d;
                    svegliaButton.Content = "disattiva sveglia";
                }
                else
                {
                    MessageBox.Show("Data della sveglia passata!", "Error", MessageBoxButton.OK);
                }
            }
            else
            {
                addSveglia = DateTime.MinValue;
                svegliaButton.Content = "attiva sveglia";
            }
        }*/

        void datePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DateTime date = (DateTime)e.NewDateTime;
            MessageBox.Show(date.ToString("d"));
        }

        void timePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            DateTime date = (DateTime)e.NewDateTime;
            MessageBox.Show(date.ToString("t"));
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if(slider1!=null)
                textBlockNote.FontSize = slider1.Value;
        }

        private void textNoteBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            textBlockNote.Text = textNoteBox.Text;
        }

        private void ListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                string selectedItem = e.AddedItems[0] as string;
                if (selectedItem != null)
                {
                    tileBackground.Background = AccentColorNameToBrush.ColorNameToBrush[selectedItem];
                    slider1.Background = AccentColorNameToBrush.ColorNameToBrush[selectedItem];
                    slider1.Foreground = AccentColorNameToBrush.ColorNameToBrush[selectedItem];
                }
            }
        }

        private void checkBox1_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            //
            textBlockNote.FontFamily = new FontFamily("font/MiasScribblings.ttf#Mia's Scribblings ~");
        }

        private void checkBox1_Unchecked(object sender, System.Windows.RoutedEventArgs e)
        {
            textBlockNote.FontFamily = new FontFamily("");
        }
    }
}